package com.rslai.commons.validator.jsonvalidator.validators;

import com.rslai.commons.validator.jsonvalidator.TYPE;
import com.rslai.commons.validator.jsonvalidator.exception.UnSupportedTypeException;
import org.hamcrest.Matchers;
import org.junit.Assert;

import java.util.List;

/**
 * JSON校验器，类型校验器
 */
public class TypeValidator extends Validator {
    public static final String VALIDATOR_NAME = "type";
    String typeStr;

    /**
     * 构造函数
     * @param args object list
     */
    public TypeValidator(List<Object> args) {
        this.typeStr = (String) args.get(0);
    }

    /**
     * 校验JSON对象
     * @param object 待验证的JSON对象
     */
    @Override
    public void doValidate(Object object) {
        if (object != null) {
            Class clazz = object.getClass();
            TYPE type = TYPE.fromType(typeStr);
            if (type == null) {
                throw new UnSupportedTypeException(String.format("the [%s] type is unsupported.", typeStr));
            }
            Class clazz1 = type.getClazz();
            if (!clazz.isAssignableFrom(clazz1)) {
                Assert.assertThat(getCurrentKeyPath(), object, Matchers.instanceOf(clazz1));
            }
        }
    }

    /**
     * 返回校验名称
     * @return 校验名称
     */
    @Override
    public String name() {
        return VALIDATOR_NAME;
    }
}
